#include <iostream>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>

int main()
{
    int fd;
    struct termios tty;
    char buffer[1024];
    ssize_t bytesRead;

    // 打开 /dev/ttyS0 串口端口
    fd = open("/dev/ttyACM0", O_RDONLY | O_NOCTTY);

    if (fd == -1)
    {
        std::cerr << "Error opening serial port." << std::endl;
        return 1;
    }

    // 配置串口参数
    if (tcgetattr(fd, &tty) != 0)
    {
        std::cerr << "Error getting serial port attributes." << std::endl;
        close(fd);
        return 1;
    }

    cfsetospeed(&tty, B9600);
    cfsetispeed(&tty, B9600);

    tty.c_cflag |= (CLOCAL | CREAD);
    tty.c_cflag &= ~PARENB;
    tty.c_cflag &= ~CSTOPB;
    tty.c_cflag &= ~CSIZE;
    tty.c_cflag |= CS8;

    tty.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
    tty.c_iflag &= ~(INPCK | ISTRIP);
    tty.c_oflag &= ~OPOST;

    tty.c_cc[VMIN] = 1;
    tty.c_cc[VTIME] = 0;

    if (tcsetattr(fd, TCSANOW, &tty) != 0)
    {
        std::cerr << "Error setting serial port attributes." << std::endl;
        close(fd);
        return 1;
    }

    // 读取串口数据并输出到控制台
    while (true)
    {
        bytesRead = read(fd, buffer, sizeof(buffer));

        if (bytesRead == -1)
        {
            std::cerr << "Error reading serial port." << std::endl;
            close(fd);
            return 1;
        }

        if (bytesRead > 0)
        {
            std::cout.write(buffer, bytesRead);
        }
    }

    // 关闭串口
    close(fd);

    return 0;
}

